<?php

/** 
 * @author Administrator
 * 
 * 
 */
class db_base {
	protected $db;
	function __construct($database) {
		$this->db = $database;
	}
	
	public function inserttable($tablename, $insertsqlarr, $returnid=0, $replace = false, $silent=0) 
	{
		$insertkeysql = $insertvaluesql = $comma = '';	
		foreach ($insertsqlarr as $insert_key => $insert_value) {
			$insertkeysql .= $comma.'`'.$insert_key.'`';
			$insertvaluesql .= $comma.'\''.$insert_value.'\'';
			$comma = ', ';
		}
	
		$method = $replace?'REPLACE':'INSERT';
		$this->db->query($method.' INTO '.tname($tablename).' ('.$insertkeysql.') VALUES ('.$insertvaluesql.')', $silent?'SILENT':'');
		if($returnid && !$replace) {
			return $this->db->insert_id();
		}
	
	}

	public function updatetable($tablename, $setsqlarr, $wheresqlarr, $silent=0) {
		$setsql = $comma = '';
		foreach ($setsqlarr as $set_key => $set_value) {
			if(is_array($set_value)) {
				$setsql .= $comma.'`'.$set_key.'`'.'='.$set_value[0];
			} else {
				$setsql .= $comma.'`'.$set_key.'`'.'=\''.$set_value.'\'';
			}
	
			$comma = ', ';
		}
	
		$where = $comma = '';
		if(empty($wheresqlarr)) {
			$where = '1';
		} elseif(is_array($wheresqlarr)) {
			foreach ($wheresqlarr as $key => $value) {
				$where .= $comma.'`'.$key.'`'.'=\''.$value.'\'';
				$comma = ' AND ';
			}
		} else {
			$where = $wheresqlarr;
		}
		$this->db->query('UPDATE '.tname($tablename).' SET '.$setsql.' WHERE '.$where, $silent?'SILENT':'');
	
	}
	
	public function getcount($tablename, $wherearr=array(), $get='COUNT(*)') {
		if(empty($wherearr)) {
			$wheresql = '1';
		} else {
			$wheresql = $mod = '';
			foreach ($wherearr as $key => $value) {
				$wheresql .= $mod."`$key`='$value'";
				$mod = ' AND ';
			}
		}
		return $this->db->result($this->db->query("SELECT $get FROM ".tname($tablename)." WHERE $wheresql LIMIT 1"), 0);
	}
		
	public static function tname($name) {
		global $_SC;
		return $_SC['tablepre'].$name;
	}
	
}

?>